package xiaoa.java.netty;

import java.util.Date;
import java.util.Iterator;
import java.util.Map.Entry;

import io.netty.buffer.ByteBuf;


import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import xiaoa.java.utils.time.DateFormatUtils;

/**
 * Created by Administrator on 2017/7/21.
 */
public class ServerHandle extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {

        if (msg instanceof HttpRequest) {
        	HttpRequest response = (HttpRequest) msg;

        	 Iterator<Entry<String, String>>  hands  =  response.headers().iterator();
        	 
        	 while (hands.hasNext()) {

        		 Entry<String, String>  e =  hands.next();
        		 System.out.println("key = " + e.getKey() + "  value = " + e.getValue());
        		 
			}
        	 
        }
        if (msg instanceof HttpContent) {
            HttpContent content = (HttpContent) msg;
            ByteBuf buf = content.content();
            System.out.println(buf.toString(io.netty.util.CharsetUtil.UTF_8));
            buf.release();
        }


        String responseBody = "当前时间：" + DateFormatUtils.format_yyyyMMddhhssSSS(new Date(System.currentTimeMillis()));

        DefaultFullHttpResponse defaultFullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1 ,HttpResponseStatus.OK );

        defaultFullHttpResponse.content().writeBytes(responseBody.getBytes());

        ctx.writeAndFlush(defaultFullHttpResponse);

    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER) //flush掉所有写回的数据
                .addListener(ChannelFutureListener.CLOSE); //当flush完成后关闭channel
    }

    public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause) {
        cause.printStackTrace();//捕捉异常信息
        ctx.close();//出现异常时关闭channel
    }

}
